package com.funny.service.impl;

import com.funny.service.RedisService;
import com.funny.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Value("${server.port}")
    private String port;
    @Autowired
    private Redisson redisson;
    @Autowired
    private RedisService redisService;

    private final Lock lock = new ReentrantLock();


    @Override
    public String queryUserInfoByName(String name) {
        String msg = "";
        lock.lock();
        try {
            // 1.查询库存信息
            String inventory001 = redisService.getCacheObject("inventory001");
//            RLock rLock = redisson.getLock("inventory001");
//            boolean tryLock = rLock.tryLock();
            if (StringUtils.isNotEmpty(inventory001)) {
                Integer inventoryNum = Integer.parseInt(inventory001);
                // 扣减库存,每次减少一个库存商品
                if (inventoryNum > 0) {
                    --inventoryNum;
                    redisService.setCacheObject("inventory001", String.valueOf(inventoryNum));
                    msg = "成功卖出一个商品,库存剩余：" + inventoryNum;
                } else {
                    msg = "商品已经售罄,库存剩余：" + inventoryNum;
                }
                log.info("操作结果:{}。该操作的服务端口为{}", msg, port);
            }

        } catch (Exception e) {
            log.error("Exception:", e);
        } finally {
            lock.unlock();
        }
        return msg + "\t" + "服务端口：" + port + "：" + name;
    }

    /**
     * 查询用户信息
     *
     * @param name 姓名
     * @return 用户信息
     */
    @Override
    public String queryUserInfo(String name) {
        log.info("查询成功,姓名：{}", name);
        return "姓名：" + name + "  |  时间：" + System.currentTimeMillis();
    }
}
